package com.baoyouqun.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baoyouqun.base.utils.ConvertUtils;
import com.baoyouqun.domain.CreateCmd.DemandInteractCreateCmd;
import com.baoyouqun.domain.Enum.DemandInteractStatusEnum;
import com.baoyouqun.domain.Enum.DemandInteractTypeEnum;
import com.baoyouqun.domain.Query.DemandInteractQuery;
import com.baoyouqun.domain.UpdateCmd.DemandInteractUpdateCmd;
import com.baoyouqun.domain.VO.DemandInteractVO;
import com.baoyouqun.entity.DemandInteract;
import com.baoyouqun.mapper.DemandInteractMapper;
import com.baoyouqun.service.DemandInteractService;
import com.baoyouqun.service.DemandService;
import jakarta.annotation.Resource;
import org.apache.poi.util.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


@Service
public class DemandInteractServiceImpl extends ServiceImpl<DemandInteractMapper, DemandInteract> implements DemandInteractService {

    @Resource
    private DemandInteractMapper demandInteractMapper;
    @Resource
    private DemandService demandService;

    @Override
    public Map<String, Integer> countValidByUserIds(List<String> userIds) {
        if (CollUtil.isEmpty(userIds)) {
            return Collections.emptyMap();
        }

        // 统计状态为"有效"的互动次数
        List<Map<String, Object>> countList = baseMapper.selectMaps(new QueryWrapper<DemandInteract>()
                .in("user_id", userIds)
                .eq("status", DemandInteractStatusEnum.VALID)  // 状态为有效（1）
                .groupBy("user_id")
                .select("user_id, count(1) as count"));

        // 转换为Map并补全所有用户ID（默认0）
        Map<String, Integer> resultMap = userIds.stream()
                .collect(Collectors.toMap(
                        Function.identity(),
                        userId -> 0
                ));

        countList.forEach(map -> {
            String userId = (String) map.get("user_id");
            Integer count = Integer.parseInt(map.get("count").toString());
            resultMap.put(userId, count);
        });

        return resultMap;
    }

    @Override
    public SingleResponse<DemandInteractVO> create(DemandInteractCreateCmd cmd) {
        DemandInteract entity =
                ConvertUtils.copyBean(cmd, DemandInteract.class);
        Boolean result = save(entity);
        if (!result) {
            return SingleResponse.buildFailure("100101", "创建失败");
        }

        DemandInteractVO vo =
                ConvertUtils.copyBean(entity, DemandInteractVO.class);
        return SingleResponse.of(vo);
    }

    @Override
    public Response update(DemandInteractUpdateCmd cmd) {
        if (Objects.isNull(cmd)) {
            return Response.buildFailure("100301", "参数不能为空");
        }
        if (StringUtil.isBlank(cmd.getId())) {
            return Response.buildFailure("100302", "ID不能为空");
        }
        DemandInteract oldEntity = getById(cmd.getId());
        if (Objects.isNull(oldEntity)) {
            return Response.buildFailure("100303", "未查询到此数据");
        }
        oldEntity = ConvertUtils.copyBean(cmd, DemandInteract.class);
        boolean result = updateById(oldEntity);
        if (result) {
            return Response.buildSuccess();
        } else {
            return Response.buildFailure("100304", "更新失败");
        }
    }

    @Override
    public DemandInteractVO selectById(String id) {
        DemandInteract entity = demandInteractMapper.selectById(id);
        DemandInteractVO vo =
                ConvertUtils.copyBean(entity, DemandInteractVO.class);
        return vo;
    }

    @Override
    public IPage<DemandInteractVO> pageVo(DemandInteractQuery query) {
        IPage<DemandInteract> page = new Page<DemandInteract>(query.getCurrent(), query.getSize());
        page = page(page, new LambdaQueryWrapper<DemandInteract>());
        Page<DemandInteractVO> voPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        List<DemandInteractVO> records = ConvertUtils.copyBeanList(page.getRecords(), DemandInteractVO.class);
        voPage.setRecords(records);
        return voPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response operate(DemandInteractCreateCmd cmd) {
        String demandId = cmd.getDemandId();
        String userId = cmd.getUserId();
        DemandInteractTypeEnum currentType = cmd.getType();
        LocalDateTime now = LocalDateTime.now();


        // 1. 查询用户对该需求的其他类型记录（互斥处理）
        LambdaQueryWrapper<DemandInteract> otherTypeWrapper = new LambdaQueryWrapper<>();
        otherTypeWrapper.eq(DemandInteract::getDemandId, demandId)
                .eq(DemandInteract::getUserId, userId)
                .ne(DemandInteract::getType, currentType); // 排除当前类型
        DemandInteract otherRecord = demandInteractMapper.selectOne(otherTypeWrapper);

        if (otherRecord != null) {
            // 删除其他类型的记录
            demandInteractMapper.deleteById(otherRecord);
            // 同步其他类型的计数器（-1）
            demandService.updateDemandInteractCount(demandId, otherRecord.getType(), -1);
        }

        // 2. 处理当前类型的操作
        LambdaQueryWrapper<DemandInteract> currentTypeWrapper = new LambdaQueryWrapper<>();
        currentTypeWrapper.eq(DemandInteract::getDemandId, demandId)
                .eq(DemandInteract::getUserId, userId)
                .eq(DemandInteract::getType, currentType);
        DemandInteract currentRecord = demandInteractMapper.selectOne(currentTypeWrapper);

        if (currentRecord == null) {
            // 新增当前类型记录
            DemandInteract newRecord = new DemandInteract();
            newRecord.setDemandId(demandId);
            newRecord.setUserId(userId);
            newRecord.setType(currentType);
            newRecord.setCreateTime(now);
            newRecord.setUpdateTime(now);
            demandInteractMapper.insert(newRecord);
            // 同步当前类型计数器（+1）

            demandService.updateDemandInteractCount(demandId, currentType, 1);
        } else {
            // 已存在当前类型记录，删除即取消
            demandInteractMapper.deleteById(currentRecord);
            // 同步当前类型计数器（-1）
            demandService.updateDemandInteractCount(demandId, currentType, -1);
        }

        return Response.buildSuccess();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response cancel(String demandId, String userId) {
        // 查询用户对该需求的记录（互斥场景下最多只有一条）
        LambdaQueryWrapper<DemandInteract> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DemandInteract::getDemandId, demandId)
                .eq(DemandInteract::getUserId, userId);
        DemandInteract record = demandInteractMapper.selectOne(queryWrapper);

        if (record == null) {
            return Response.buildFailure("100301", "未进行过点赞/点踩操作，无法取消");
        }

        // 删除记录
        demandInteractMapper.deleteById(record);

        // 同步计数器（-1）
        demandService.updateDemandInteractCount(demandId, record.getType(), -1);
        return Response.buildSuccess();
    }

    @Override
    public List<Map<String, Object>> queryUserActions(String currentUserId, List<String> demandIds) {
        if (StringUtil.isBlank(currentUserId) || CollUtil.isEmpty(demandIds)) {
            return new ArrayList<Map<String, Object>>();
        }
        return demandInteractMapper.queryUserActions(currentUserId, demandIds);
    }

    public DemandInteract selectByDemandIdUserId(String demandId, String userId) {
        return getOne(new LambdaQueryWrapper<DemandInteract>()
                .eq(DemandInteract::getDemandId, demandId)
                .eq(DemandInteract::getUserId, userId)
                .last("limit 1"));

    }
}